package com.sharecode.stock.thread;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.sharecode.stock.aop.ParamData;

public class ThreadLocalUtils {
	private static final ThreadLocal<HttpServletRequest> request = new ThreadLocal<>();
	private static final ThreadLocal<HttpServletResponse> response = new ThreadLocal<>();
	private static final ThreadLocal<ConcurrentHashMap<String, String>> param = new ThreadLocal<>();

	public static void init(HttpServletRequest req, HttpServletResponse res) {
		request.set(req);
		response.set(res);
		param.set(new ConcurrentHashMap<>());
	}

	public static void initParam() {
		Set<Map.Entry<String, String[]>> entries = request.get().getParameterMap().entrySet();
		ConcurrentHashMap<String, String> map = param.get();
		for (Map.Entry<String, String[]> entry : entries) {
			String value = entry.getValue()[0];
			if (StringUtils.isNotBlank(value)) {
				map.put(entry.getKey(), value);
			}
		}
	}

	public static HttpServletRequest getRequest() {
		return request.get();
	}

	public static Map<String, String> getParam() {
		return param.get();
	}

	public static String getParam(String key) {
		return param.get().get(key);
	}

	public static HttpServletResponse getResponse() {
		return response.get();
	}

	public static ParamData getParamData() {
		return JSONObject.parseObject(JSONObject.toJSONString(param.get()), ParamData.class);
	}

	public static void remove() {
		request.remove();
		response.remove();
		param.remove();
	}
}
